package ai.zixing.powermock.mockskip.service;

import ai.zixing.powermock.mockskip.common.Errors;
import ai.zixing.powermock.mockskip.domain.User;
import ai.zixing.powermock.mockskip.repository.UserRepository;
import com.github.jsonzou.jmockdata.util.StringUtils;

/**
 * @author zixing
 */
public class UserServiceImpl implements UserService{

    private final UserRepository userRepository;

    private final UserSettingService userSettingService;

    private final MainClient mainClient;

    public UserServiceImpl(UserRepository userRepository, UserSettingService userSettingService, MainClient mainClient) {
        this.userRepository = userRepository;
        this.userSettingService = userSettingService;
        this.mainClient = mainClient;
    }

    @Override
    public User register(User user) {
        // 验证注册用户不通过则返回错误原因
        String validateResult = validate(user);
        if (StringUtils.isNotEmpty(validateResult)) {
            throw new RuntimeException(validateResult);
//            return new User("ziyue", 18);
        }
        // 入库
        User insertUser = userRepository.insert(user);
        // 发送邮件
        mainClient.sendUserRegistrationMail(insertUser);
        return insertUser;
    }

    /**
     * 用户注册信息验证
     *
     * @param user user
     * @return String
     */
    private String validate(User user) {
        StringBuilder sb = new StringBuilder();
        if (user.getName() == null) {
            sb.append(Errors.USER_NAME_REQUIRED).append(Errors.SPLIT_FLAG);
        }
        if (user.getName().length() < userSettingService.getUserNameMinLength()) {
            sb.append(Errors.USER_NAME_SHORT).append(Errors.SPLIT_FLAG);
        }
        if (user.getAge() < userSettingService.getUserMainAge()) {
            sb.append(Errors.USER_AGE_YOUNG).append(Errors.SPLIT_FLAG);
        }
        if (userRepository.isUserNameAlreadyExists(user.getName())) {
            sb.append(Errors.USER_NAME_DUPLICATE).append(Errors.SPLIT_FLAG);
        }
        return sb.toString();
    }
}
